# -*- coding: utf-8 -*-
#import cgi
import os
import re
import json
import time
import urllib2
import socket
from datetime import datetime
import pywintypes
# First import two useful modules
from win32com.client import Dispatch
#from adoconstants import *

telecom="61.153.145.162:8888"
cnc="221.12.55.171:8889"
mlip=telecom
#http://61.153.145.162:8888/getpositionTP.asp?regnum=浙B8E792
#http://61.153.145.162:8888/getpositionTP.asp?regnum=all
#电信地址
#http://221.12.55.171:8889/getpositionTP.asp?regnum=浙B8E792
#网通地址
#http://61.153.145.162:8888/getpositionTPM.asp?regnum=浙B8E792
# 跳转到51ditu
# http://61.153.145.162:8888/HQWEBGPS/WEBGIS/51dtA.htm?浙B8F661,2011年7月28日9:08:25,18,121.496198,30.121058
# 请求地址

# http://rgc.vip.51ditu.com/rgc?pos=12086389,3014611&type=1
# 反向地址解释地址，经度范围为7340000～13657591,纬度范围为323936～5523685

# <?xml version="1.0" encoding="GBK" ?><R> <code>0</code> <msg>浙江省绍兴市上虞市，纬三路和经九路交叉口西约120米处, 杭州湾精细化工园区公园西北约660米处</msg> </R>

# http://rgc.vip.51ditu.com/rgc?pos=12086389,3014611
# <?xml version="1.0" encoding="GBK" ?> <ReverseGeocode> <Geo lng="12086389"  lat="3014611"/> <Area regionCode="330682"> 浙江省-绍兴市-上虞市</Area> </ReverseGeocode>

def adjust():
	h=datetime.now().hour
	if(h>=0 and h<=6) or (h>=20 and h<=23):
		timecheck=300
	else:
		timecheck=30
	return timecheck
	
def mlurl(ip):
	return "http://"+ip+"/getpositionTP.asp?regnum=all"

def writelog():
	logfilename=datetime.strftime(datetime.now(),"%Y%m%d")+".log"
	try:
		f=open('log'+os.sep+'getmlgps'+os.sep+logfilename,'a')
		try:
			f.write(datetime.strftime(datetime.now(),"%Y/%m/%d %H:%M:%S")+"\n")
		finally:
			f.close()
	except IOError:
		pass
		
def save_mlgps(jdata):
	oConn = Dispatch('ADODB.Connection')
	oConn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=data\data.mdb;Jet OLEDB:Database Password=tp@chenkai"
	oConn.Open()
	oCmd = Dispatch('ADODB.Command')
	oCmd.ActiveConnection = oConn
	for x in jdata:
		print x
		cph=x['LicensePlate']
		print cph
		cl_lng=str(x['Geometry']['Coordinates'][0])
		cl_lat=str(x['Geometry']['Coordinates'][1])
		cl_timestamp=str(x['TimeStamp'])
		cl_speed=str(x['Speed'])
		cl_update=datetime.strftime(datetime.now(),"%Y/%m/%d %H:%M:%S")
		cl_reverse=getreverse(x['Geometry']['Coordinates'])
		oCmd.CommandText = "update cl set cl_lng="+cl_lng+",cl_lat="+cl_lat+",cl_timestamp="+cl_timestamp+",cl_speed="+cl_speed+",cl_update=\'"+cl_update+"\',cl_reverse=\'"+cl_reverse+"\' where cph=\'"+cph+"\'"
		print oCmd.CommandText
		
		oCmd.Execute()
	writelog()
	oCmd = None
	oConn.Close()
	oConn = None

def formatgeo(geo):
	s=str(round(geo,5))
	l=s.split(".")
	if len(l[1])>=5:
		l[1]=l[1][:5]
	else:
		l[1]=l[1]+"0"*(5-len(l[1]))
	# print l[1]
	s="".join(l)
	return s
		
def getreverse(lnglat):
	lng=formatgeo(lnglat[0])
	lat=formatgeo(lnglat[1])
	url="http://rgc.vip.51ditu.com/rgc?pos="+lng+","+lat+"&type=1"
	print url
	req = urllib2.Request(url)
	response = urllib2.urlopen(req)
	the_page = response.read()
	response.close()
	pattern=r'<msg>.+?<\/msg>'
	reverse=re.search(pattern,the_page).group(0)
	pattern=r'<.+?>'
	reverse=re.sub(pattern,'',reverse)
	reverse=unicode(reverse,"gbk")
	pattern=u'浙江省'
	reverse=re.sub(pattern,'',reverse)
	print reverse
	return reverse	


	

while True:
	print "starting..."
	#print mlurl(mlip)
	req = urllib2.Request(mlurl(mlip))
	try:
		response = urllib2.urlopen(req)
	except IOError,e:
		#if hasattr(e,'reason'):
			#print e.reason
		#elif hasattr(e,'code'):
			#print e.code
		mlip=cnc
		continue
	try:
		the_page = response.read()
		response.close()
	except socket.error:
		continue
	try:
		s=the_page[1:len(the_page)-1]
		j=json.loads(s)
		save_mlgps(j)
		# print j
	except:
		#print "pass"
		pass
	time.sleep(adjust())
